package com.example.eddie.test.ConnectionWeb;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Connection {

    private static final String TAG = "ConnectionTest";

    private String cookie;

    public String getString(String urlString,String referer,String teacherId,String yzm) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Referer",referer);
        connection.setRequestProperty("Cookie",cookie);
        postSearchInfo(connection,teacherId,yzm);
        String SearchResult = getSearchResult(connection);
        return SearchResult;
    }

    private String getSearchResult(HttpURLConnection connection){
        StringBuilder sb = null;
        try {
            InputStream is = connection.getInputStream();
            BufferedReader bf = new BufferedReader(new InputStreamReader(is,"GB2312"));
            sb = new StringBuilder();
            String info;
            while ((info = bf.readLine())!=null) {
                sb.append(info);
            }

            is.close();bf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (sb != null) {
            return sb.toString();
        }else {
            return "";
        }

    }

    public void postSearchInfo(HttpURLConnection connection,String teacherID,String yzm){
        try {
            OutputStream os = connection.getOutputStream();
            String postInfo = "Sel_XNXQ=20170" + "&" + "Sel_JS="+teacherID.split("\\?")[1]+  "&" + "type=1&" + "txt_yzm="+yzm;
            os.write(postInfo.getBytes());
            os.flush();os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };

    public Bitmap initImg(String ImgURL,String Referer){
        try {
            URL url = new URL(ImgURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.addRequestProperty("Referer",Referer);
            InputStream is = connection.getInputStream();
            final Bitmap bitmap = BitmapFactory.decodeStream(is);
            String headerField = connection.getHeaderField("set-cookie");
            cookie = headerField.split(";")[0];
            return bitmap;
        }catch (IOException e){
            e.printStackTrace();
        }

        return null;
    }

}
